<!-- Banner管理 -->
<template>
  <div id="BannerIndex">
    <main-header :title="'Banner管理'" :crumbsArr="crumbsArr" />
    <div class="banner_index_main">
      <el-tabs
        type="border-card"
        v-model="currentTab"
        @tab-click="clickTab(currentTab)"
      >
        <el-tab-pane
          v-for="item in tabsConfig"
          :key="item.id"
          :label="item.name"
          :name="item.id"
        >
          <!-- 表格组件 -->
          <banner-table
            :tabConfigAndData="item"
            @addOneBannerClick="addOneBannerClick"
            @deleteOneBannerClick="deleteOneBannerClick"
            @editOneBannerClick="editOneBannerClick"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- dialog 删除banner -->
    <el-dialog
      title="提示"
      :visible.sync="delConfirmDialogVisible"
      width="30%"
    >
      <span>删除该banner？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delConfirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteOneBannerOk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- dialog 新增banner -->
    <el-dialog
      :title="addOrEditTitle"
      :visible.sync="addOneDialogVisible"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="图片">
          <ul v-loading="picLoading" class="add_pic_wrapper">
            <li v-if="addForm.itemBg">
              <div class="add_pic_block">
                <img width="160px" height="80px" :src="addForm.itemBg | handlePicSize('160', '80')" alt="">
                <div class="hover_delete">
                  <el-button type="danger" icon="el-icon-delete" circle @click="deletePic"></el-button>
                </div>
              </div>
            </li>
            <li v-if="!(addForm.itemBg)">
              <div>
                <input
                  ref="addPicInput"
                  type="file" name="addPicInput"
                  style="display: none;"
                  accept="image/*"
                  @change="addPicInputChange('addPicInput')">
                <el-button
                  class="add_pic_btn"
                  @click="clickAddPic('addPicInput')">
                  <i class="el-icon-plus"></i>
                </el-button>
              </div>
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="类型" prop="region">
          <el-select v-model="addForm.selectType" placeholder="请选择活动区域">
            <el-option label="商品" value="商品"></el-option>
            <el-option label="活动" value="活动"></el-option>
            <el-option label="外链" value="外链"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="addForm.customDescName" prop="customDesc">
          <el-input v-model="addForm.customDesc"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input v-model="addForm.priority"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOneBannerDialogClose('addForm')">取 消</el-button>
        <el-button type="primary" @click="addOneBannerOk('addForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js'
import MainHeader from '@/components/layouts/MainHeader'
import BannerTable from '@/components/pages/banner/BannerTable'
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'
export default {
  name: 'BannerIndex',
  components: {
    MainHeader,
    BannerTable
  },
  beforeRouteEnter (to, from, next) {
    next(vm => vm.initPage())
  },
  data () {
    const validatePriority = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入优先级，值为正整数'))
      } else {
        let reg = /^[1-9]*$/
        if (window.isNaN(value) || !reg.test(value)) {
          callback(new Error('优先级为正整数，您的输入有误'))
        }
        const currentTableData = this.tabsConfig[this.currentTab].tableData
        console.log(this.beHandlingTableItemInfo)
        for (let item of currentTableData) {
          if ((item.priority === Number.parseInt(value)) && (this.beHandlingTableItemInfo.id !== item.id)) {
            callback(new Error(`已有优先级为${value}的Banner，请重新输入`))
            break
          }
        }
        callback()
      }
    }

    const validateDesc = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(`请输入${this.addForm.customDescName}`))
      } else {
        switch (this.addForm.selectType) {
          case '商品':
          case '活动':
            if (window.isNaN(value)) {
              callback(new Error(`${this.addForm.customDescName}为数字值，您的输入有误`))
            }
            break
          case '外链':
            let urlReg = // 网址正则
              /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$/
            if (!urlReg.test(value)) {
              callback(new Error(`您输入的网址有误`))
            }
            break
        }
        callback()
      }
    }

    return {
      crumbsArr: [ // 面包屑
        { name: 'welcome', txt: '首页' }, { txt: 'Banner管理' }
      ],
      currentTab: '0',
      tabsConfig: [ // tabs参数
        {
          id: '0',
          name: '首页banner',
          tableData: null,
          tableLoading: false,
          emptyTxt: '暂无首页banner数据',
          type: 1
        },
        {
          id: '1',
          name: '商城banner',
          tableData: null,
          tableLoading: false,
          emptyTxt: '暂无商城banner数据',
          type: 8
        }
      ],
      beHandlingTableItemInfo: null, // 当前操作的row信息
      delConfirmDialogVisible: false, // 删除banner的dialog visible
      addOneDialogVisible: false, // 新增banner的dialog visible
      addForm: {
        itemBg: '',
        selectType: '商品',
        customDesc: '',
        customDescName: '商品ID',
        itemId: '', // 商品 ID
        itemDesc: '', // 活动ID
        itemUrl: '', // 外链
        type: null,
        priority: null
      },
      emptyAddForm: { // 空的表单，只是为了方便情况表单数据
        itemBg: '',
        selectType: '商品',
        customDesc: '',
        customDescName: '商品ID',
        itemId: '', // 商品 ID
        itemDesc: '', // 活动ID
        itemUrl: '', // 外链
        type: null,
        priority: null
      },
      addFormRules: {
        priority: [
          { required: true, validator: validatePriority, trigger: 'blur' }
        ],
        customDesc: [
          { required: true, validator: validateDesc, trigger: 'blur' }
        ]
      },
      picLoading: false, // 上传图片loading
      addOrEditTitle: '',
      isAddDialog: true
    }
  },
  filters: {
    handlePicSize: (picPath, width, height) => {
      return `${picPath}?imageView2/1/w/${width}/h/${height}`
    }
  },
  watch: {
    // '$route' (to, from) {
    //   if (to.name === 'banner') {
    //     this.initPage()
    //   }
    // },
    'addForm.selectType' (val, oldVal) {
      switch (val) {
        case '商品':
          this.addForm.customDescName = '商品ID'
          break
        case '活动':
          this.addForm.customDescName = '活动ID'
          break
        case '外链':
          this.addForm.customDescName = '超链接'
          break
      }
    },
    'addForm.customDesc' (val, oldVal) {
      switch (this.addForm.selectType) {
        case '商品':
          this.addForm.itemId = val
          this.addForm.itemDesc = ''
          this.addForm.itemUrl = ''
          break
        case '活动':
          this.addForm.itemId = ''
          this.addForm.itemDesc = val
          this.addForm.itemUrl = ''
          break
        case '外链':
          this.addForm.itemId = ''
          this.addForm.itemDesc = ''
          this.addForm.itemUrl = val
          break
      }
    }
  },
  methods: {
    initPage () { // 初始化页面
      this.loadTableData()
    },
    async loadTableData (tabNum = this.currentTab) { // 加载数据
      tabNum = Number.parseInt(tabNum)
      const tabConfig = this.tabsConfig[tabNum]
      const { type } = tabConfig
      tabConfig.tableLoading = true
      const response = await API.getBannerList({ type })
      const { code, data } = response
      if (code === 1) {
        tabConfig.tableData = data
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
      tabConfig.tableLoading = false
    },
    clickTab () { // 点击tab页
      this.loadTableData()
    },
    resetAddEditForm (formName) { // 重置表单
      this.$refs[formName].resetFields()
      this.addForm = Object.assign({}, this.emptyAddForm)
    },
    addOneBannerClick () { // 添加按钮点击
      this.isAddDialog = true
      const tableData = this.tabsConfig[Number.parseInt(this.currentTab)].tableData
      if (tableData.length >= 6) {
        this.$message({
          message: '只能添加6个banner',
          type: 'warning'
        })
        return false
      }
      this.addOrEditTitle = '新增'
      this.addOneDialogVisible = true
    },
    deletePic () { // 删除图片
      this.addForm.itemBg = ''
    },
    deleteOneBannerClick (id, index) { // 删除按钮点击
      this.beHandlingTableItemInfo = Object.assign({}, { id, index })
      this.delConfirmDialogVisible = true
    },
    async deleteOneBannerOk () { // 删除确认
      const { id, index } = this.beHandlingTableItemInfo
      this.delConfirmDialogVisible = false
      const tabConfig = this.tabsConfig[Number.parseInt(this.currentTab)]
      tabConfig.tableLoading = true
      const response = await API.deleteOneBanner({ id }) // api
      const { code } = response
      if (code === 1) {
        tabConfig.tableData.splice(index, 1)
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
      tabConfig.tableLoading = false
    },
    async editOneBannerClick (id, index) { // 编辑按钮点击
      this.isAddDialog = false // 表示是编辑
      this.beHandlingTableItemInfo = Object.assign({}, { id, index })
      this.addOrEditTitle = '编辑'

      // 查询详情数据并填充
      const tabConfig = this.tabsConfig[Number.parseInt(this.currentTab)]
      tabConfig.tableLoading = true
      const detailData = await API.getBannerDetail({ id })
      const { code, data } = detailData
      if (!code) { tabConfig.tableLoading = false; return false }
      if (code === 1) {
        const { itemBg, itemDesc, itemId, itemUrl, type, priority } = data
        let [ selectType, customDescName, customDesc ] = [ '', '', itemId || itemDesc || itemUrl ]
        if (itemId) {
          selectType = '商品'
          customDescName = '商品ID'
        }
        if (itemDesc) {
          selectType = '活动'
          customDescName = '活动ID'
        }
        if (itemUrl) {
          selectType = '外链'
          customDescName = '超链接'
        }
        let detailForm = {
          id,
          itemBg,
          selectType,
          customDescName,
          itemId, // 商品 ID
          itemDesc, // 活动ID
          itemUrl, // 外链
          type,
          priority
        }
        this.addForm = Object.assign({}, detailForm)
        this.addForm.customDesc = customDesc
      } else {
        this.$message.error(ErrorConfig[code])
      }
      tabConfig.tableLoading = false

      this.addOneDialogVisible = true
    },
    clickAddPic (fileInput) {
      this.$refs[fileInput].click()
    },
    async addPicInputChange (fileInput) {
      this.picLoading = true
      const response = await API.getQiNiuToken()
      const qiniuConfig = { // 七牛云上传参数
        file: this.$refs[fileInput].files[0],
        key: new Date().getTime(),
        token: response.data,
        putExtra: {
          fname: '',
          params: {},
          mimeType: [] || null
        },
        config: {
          useCdnDomain: true
        }
      }

      // 注入七牛参数
      let observable =
        qiniu.upload(qiniuConfig.file, qiniuConfig.key, qiniuConfig.token, qiniuConfig.putExtra, qiniuConfig.config)

      // 开始上传
      observable.subscribe(undefined, (errmsg) => {
        this.picLoading = false
        this.$message.error('图片上传失败，请重试')
      }, async (res) => {
        this.picLoading = false
        this.addForm.itemBg = `${API.FILE_HOST_URL}${res.key}`
        // const resData = await API.getDownloadUrl(`${API.FILE_HOST_URL}${res.key}`) // 获取图片路径
        // if (resData.code === 1) {
        //   this.addForm.itemBg = resData.data
        // } else {
        //   this.$message.error(ErrorConfig[resData.code])
        // }
      })
    },
    addOneBannerDialogClose (formName) { // 添加banner dialog关闭
      this.addOneDialogVisible = false

      this.resetAddEditForm(formName)

      this.addForm.itemBg = ''
    },
    addOneBannerOk (formName) { // 添加banner dialog确认
      this.$refs[formName].validate(async (valid) => {
        if (valid) { // 表单校验通过
          if (!this.addForm.itemBg) {
            this.$message.error('请添加图片')
            return false
          } else {
            this.addOneDialogVisible = false
            this.addForm.type = this.tabsConfig[window.parseInt(this.currentTab)].type
            let response = null
            if (this.addOrEditTitle === '新增') {
              response = await API.addOneBanner(this.addForm)
            } else {
              response = await API.editBanner(this.addForm)
            }
            const { code } = response
            if (code === 1) {
              this.loadTableData()
            } else {
              this.$message.error(ErrorConfig[code])
            }

            this.resetAddEditForm(formName)
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .clearfix {
    display: block;
    &:after {
      display: block;
      content: ".";
      height: 0;
      line-height: 0;
      clear: both;
      visibility: hidden;
    }
  }
  .banner_index_main {
    padding: 20px 20px 0;
  }
  ul.add_pic_wrapper {
    margin: 0;
    padding: 0;
    list-style: none;
    @extend .clearfix;
    li {
      float: left;
      margin: 0 20px 10px 0;
      position: relative;
      &:hover {
        .hover_delete {
          display: block;
        }
      }
      .add_pic_block {
        height: 80px;
      }
      .add_pic_btn {
        width: 160px;
        height: 80px;
      }
      .hover_delete {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, .3);
        .el-button {
          position: absolute;
          top: 50%;
          left: 50%;
          -webkit-transform: translate(-50%, -50%);
          -moz-transform: translate(-50%, -50%);
          -ms-transform: translate(-50%, -50%);
          -o-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
        }
      }
    }
  }
</style>
